package com.aisino.api.service;

import com.aisino.api.model.DevLog;
import com.aisino.api.util.CommonCryptogramUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class DevLogService {
    
    private static final Logger logger = LoggerFactory.getLogger(DevLogService.class);
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    /**
     * 保存接口调用日志
     * @param devLog 日志对象
     */
    public void saveLog(DevLog devLog) {
        try {
            creatLogSignValue(devLog);
            String sql = "INSERT INTO YGYD_SYS.DEV_LOG (" +
                    "ID, CATEGORY, NAME, EXE_STATUS, EXE_MESSAGE, OP_IP, OP_ADDRESS, OP_BROWSER, " +
                    "OP_OS, CLASS_NAME, METHOD_NAME, REQ_METHOD, REQ_URL, PARAM_JSON, RESULT_JSON, " +
                    "OP_TIME, OP_USER, SIGN_DATA, CREATE_TIME, CREATE_USER, UPDATE_TIME, UPDATE_USER, " +
                    "QYID, DQBM, TABLES, SQL) " +
                    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            
            jdbcTemplate.update(sql,
                    devLog.getId(), // 限制ID长度为20字符
                    devLog.getCategory(),
                    devLog.getName(),
                    devLog.getExeStatus(),
                    devLog.getExeMessage(),
                    devLog.getOpIp(),
                    devLog.getOpAddress(),
                    devLog.getOpBrowser(),
                    devLog.getOpOs(),
                    devLog.getClassName(),
                    devLog.getMethodName(),
                    devLog.getReqMethod(),
                    devLog.getReqUrl(),
                    devLog.getParamJson(),
                    devLog.getResultJson(),
                    devLog.getOpTime(),
                    devLog.getOpUser(),
                    devLog.getSignData(),
                    devLog.getCreateTime(),
                    devLog.getCreateUser(),
                    devLog.getUpdateTime(),
                    devLog.getUpdateUser(),
                    devLog.getQyid(),
                    devLog.getDqbm(),
                    devLog.getTables(),
                    devLog.getSql()
            );
        } catch (Exception e) {
            // 记录日志保存失败的异常，但不中断主流程
            logger.error("保存接口调用日志失败", e);
        }
    }

    /**
     * 构建日志完整性保护签名数据
     */
    private static void creatLogSignValue (DevLog devLog) {
        String logStr = devLog.toString().replaceAll(" +","");
        devLog.setSignData(CommonCryptogramUtil.doSignature(logStr));
    }
}